//
//  FriendDetailViewController.m
//  Light
//
//  Created by MiaoYe on 15/10/23.
//  Copyright © 2015年 骁唐. All rights reserved.
//

#import "FriendDetailViewController.h"
#import "UserConfig.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "constantDefinition.h"
#import "UIImageView+WebCache.h"
#import "LoginViewController.h"
@interface FriendDetailViewController ()<MBProgressHUDDelegate,UIAlertViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
@property (weak, nonatomic) IBOutlet UITextField *noteTextField;

@end

@implementation FriendDetailViewController
{
    UIAlertView *alert;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [_headImage.layer setMasksToBounds:YES];
    [_headImage.layer setCornerRadius:35.0f];
    [self getFriendInfo];
    MBPROGRESS_ALLOC;
    self.noteTextField.text = self.friendInfo[@"remarks"];//remarks-备注   Name-昵称
    self.noteTextField.delegate = self;
    self.userNumber.text = self.friendInfo[@"cellPhone"];
    self.nickName.text = self.friendInfo[@"remarks"];
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark -
#pragma mark 获取好友资料
- (void)getFriendInfo {
    [_mbProgressHud show:YES];
    
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    __weak FriendDetailViewController *weakSelf =  self;
    NSDictionary *dic = @{@"Token":[userConfig getToken],@"friend":_friendInfo[@"friend"]};
    //地址
    [httpManager POST:FRIEND_DETAIL parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"获取成功");
                  //处理后台返回空字段
                  NSMutableString *string = [NSMutableString stringWithString:dic[@"b"]];
                  [string replaceOccurrencesOfString:@"null" withString:@"\"\"" options:NSLiteralSearch range:NSMakeRange(0, string.length)];
                  NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:string];
                  NSMutableArray *resArr = (NSMutableArray *)resDic;
                  NSDictionary *friendDic = resArr[0];
                  if ([dic[@"a"] intValue] == 1) {
                      NSLog(@"获取成功");
                      weakSelf.userName.text = friendDic[@"Name"];  //remarks-备注   Name-昵称
                      weakSelf.userNumber.text = weakSelf.friendInfo[@"cellPhone"];
                      NSString *urlstr = [NSString stringWithFormat:@"%@/up/%@",SERVER_KEY,friendDic[@"headPortrait"]] ;
                      weakSelf.placeLabel.text = weakSelf.friendInfo[@"region"];
                      [weakSelf.headImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"user - head"]];
                      weakSelf.todayScore.text =[NSString stringWithFormat:@"%@",friendDic[@"todaypoint"]] ;
                      weakSelf.totalScore.text = [NSString stringWithFormat:@"%@",friendDic[@"totalpoints"]];
                  }
                  else if ([dic[@"a"] intValue] == -1)
                  {
                      if (TJJiOS8)
                      {
                          UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                          
                          [self presentViewController:Alertview animated:YES completion:nil];
                          
                          UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                              
                              UserConfig *config = [UserConfig sharingUserConfig];
                              [config setHaveLogin:@"lalala"];
                              [config setToken:@"123"];
                              [config setUserHeadData:nil];
                              
                              UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                              LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                              loginVc.quit = YES;
                              [self.navigationController pushViewController:loginVc animated:YES];
                          }];
                          
                          [Alertview addAction:action];
                      }
                      else
                      {
                          UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                          alertView.tag = 97;
                          [alertView show];
                      }
                  }else if ([dic[@"a"] intValue] == 0) {
                      
                      ALERT_VIEW(@"获取失败");
                  }
                  _mbProgressHud.hidden = YES;
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"信息获取失败");
                  _mbProgressHud.hidden = YES;
                  
              }];
    
}

#pragma mark -
#pragma mark 更新备注姓名
-(void)updateNoteName
{
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    UserConfig *userConfig = [UserConfig sharingUserConfig];
//    __weak FriendDetailViewController *weakSelf =  self;
    NSDictionary *dic = @{@"Token":[userConfig getToken],@"personalized":self.noteTextField.text,@"friend":self.friendInfo[@"friend"]};
    //地址
    [httpManager POST:FRIEND_UPDATE_NAME parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
                  if ([dic[@"a"] intValue] == 1) {
                      
                      NSLog(@"获取成功");
                      
                      
                  }else if ([dic[@"a"] intValue] == -1) {
                      NSLog(@"token无效");
                      
                  }else if ([dic[@"a"] intValue] == 0) {
                    
                  }
                  
                  _mbProgressHud.hidden = YES;
                  
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"网络连接超时");
                  
                  _mbProgressHud.hidden = YES;
                  
              }];

}

#pragma mark -
#pragma mark 导航返回
- (IBAction)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self updateNoteName];//更新好友备注
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];//回收键盘
    return YES;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 97:
        {//重新登录
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        default:
            break;
    }
}
@end
